package com.jt.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jt.mapper.CartMapper;
import com.jt.pojo.Cart;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@Service
public class CartServerImpl implements DubboCartService {

    @Autowired
    private CartMapper cartMapper;

    //根据userId查询购物车记录
    @Override
    public List<Cart> findCartList(Long userId) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        return cartMapper.selectList(queryWrapper);
    }


    /**
     * 目的: 修改购物车数量
     * @param cart
     */
    @Override
    public void updateCartNum(Cart cart) {
        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("user_id",cart.getUserId())
                     .eq("item_id",cart.getItemId());
        Cart cartTemp = new Cart();
        cartTemp.setNum(cart.getNum()).setUpdated(new Date());
        cartMapper.update(cartTemp,updateWrapper);
    }

    //删除购物车的商品
    @Override
    public void deleteCart(Cart cart) {
        //将对象中不为null的元素当做where条件
        cartMapper.delete(new QueryWrapper<>(cart));
    }


    //如果重复添加,则更新数量
    //如何判断是否为重复添加  item_id/user_id
    @Override
    public void insertCart(Cart cart) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",cart.getUserId())
                    .eq("item_id",cart.getItemId());
        Cart cartDb = cartMapper.selectOne(queryWrapper);
        if (cartDb==null){
            //表示用户第一次新增
            cart.setCreated(new Date()).setUpdated(cart.getCreated());
            cartMapper.insert(cart);
        }else {
            //表示用户重复加购
            int num = cart.getNum() + cartDb.getNum();
            Cart cartTemp = new Cart();
            cartTemp.setNum(num).setUpdated(new Date());
            cartMapper.update(cartTemp,queryWrapper);
        }
    }

}
